package cn.uncode.springcloud.starter.web.configuration;


import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.servlet.DispatcherType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.uncode.springcloud.utils.json.MappingApiJackson2HttpMessageConverter;
import cn.uncode.springcloud.utils.support.xss.XssFilter;
import lombok.extern.slf4j.Slf4j;

/**
 * 配置类
 *
 * @author Juny
 */
@Slf4j
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CommonWebAutoConfiguration implements WebMvcConfigurer {
	
	
	@Autowired
	private ObjectMapper objectMapper;
	
	/**
	 * 使用 JACKSON 作为JSON MessageConverter
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.removeIf(x -> x instanceof StringHttpMessageConverter || x instanceof MappingJackson2HttpMessageConverter);
		converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		converters.add(new MappingApiJackson2HttpMessageConverter(objectMapper));
	}
	

	/**
	 * 防XSS注入
	 *
	 * @return FilterRegistrationBean
	 */
	@Bean
	public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
		FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<XssFilter>();
		registration.setDispatcherTypes(DispatcherType.REQUEST);
		registration.setFilter(new XssFilter());
		registration.addUrlPatterns("/*");
		registration.setName("xssFilter");
		registration.setOrder(Ordered.LOWEST_PRECEDENCE);
		log.info("===Uncode-starter===CommonWebAutoConfiguration===>XssFilter registed...");
		return registration;
	}

    
    



}
